package upload

import (
	"fmt"
	"fx_swift_boss/pkg/global"
	"fx_swift_boss/pkg/logger"
	"fx_swift_boss/pkg/utils"
	"github.com/aws/aws-sdk-go/aws"
	"github.com/aws/aws-sdk-go/aws/credentials"
	"github.com/aws/aws-sdk-go/aws/session"
	"github.com/aws/aws-sdk-go/service/s3/s3manager"
	"github.com/gin-gonic/gin"
	"io"
	"strings"
)

func UploadToS3Srv(fileName string, f io.Reader) (string, error) {
	var (
		err error
	)

	sess, _ := session.NewSession(&aws.Config{
		Credentials: credentials.NewStaticCredentials(
			global.ViperObj.GetString("aws.access_key_id"),
			global.ViperObj.GetString("aws.secret_access_key"), ""),
		Region:           aws.String(global.ViperObj.GetString("aws.s3_region")),
		DisableSSL:       aws.Bool(true),
		S3ForcePathStyle: aws.Bool(false), //virtual-host style方式，不要修改
	})

	// upload path
	uploader := s3manager.NewUploader(sess)
	_, err = uploader.Upload(&s3manager.UploadInput{
		Bucket: aws.String(global.ViperObj.GetString("aws.s3_buket")),
		Key:    aws.String(fileName),
		Body:   f,
	})
	if err != nil {
		logger.SugarLogger.Error(err)
	}
	path := fmt.Sprintf("https://cs-pic.s3.ap-southeast-1.amazonaws.com/%s", fileName)
	return path, err
}

func UploadFile(ctx *gin.Context) ([]string, error) {
	var (
		err    error
		result = make([]string, 0)
	)
	// 读取前端传的多个文件
	form, _ := ctx.MultipartForm()
	files := form.File["files"]

	sess, _ := session.NewSession(&aws.Config{
		Credentials: credentials.NewStaticCredentials(
			global.ViperObj.GetString("aws.access_key_id"),
			global.ViperObj.GetString("aws.secret_access_key"), ""),
		Region:           aws.String(global.ViperObj.GetString("aws.s3_region")),
		DisableSSL:       aws.Bool(true),
		S3ForcePathStyle: aws.Bool(false), //virtual-host style方式，不要修改
	})

	for _, file := range files {
		// 读取文件
		f, _ := file.Open()
		defer f.Close()

		// 重写赋值名称
		fileName := utils.GenerateCode64()
		// 获取文件扩展名
		fileExt := GetFileExt(file.Filename)
		// upload path
		uploader := s3manager.NewUploader(sess)
		_, err = uploader.Upload(&s3manager.UploadInput{
			Bucket: aws.String(global.ViperObj.GetString("aws.s3_buket")),
			Key:    aws.String(fileName + fileExt),
			Body:   f,
		})
		if err != nil {
			logger.SugarLogger.Error(err)
		}
		path := fmt.Sprintf("https://cs-pic.s3.ap-southeast-1.amazonaws.com/%s", fileName+fileExt)
		result = append(result, path)
	}
	return result, err
}

func GetFileExt(fileName string) string {
	return fileName[strings.LastIndex(fileName, "."):]
}
